package com.spdzen.support;

import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class JsonUtils {
	private static final String DEFAULT_CALLBACK = "callback";

	private static SerializerFeature[] features = new SerializerFeature[] { SerializerFeature.WriteMapNullValue,
			SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteNullListAsEmpty,
			SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullStringAsEmpty,
			SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteNonStringKeyAsString };

	public static String toJSONString(Object obj) {
		return JSON.toJSONString(obj, features);
	}

	public static String toJSONPString(Object obj, String callback) {
		if (StringUtils.isBlank(callback)) {
			callback = DEFAULT_CALLBACK;
		}

		StringBuilder sb = new StringBuilder();
		sb.append(callback).append("(").append(toJSONString(obj)).append(");");
		return sb.toString();
	}

	public static String toJSONString(Object... objects) {
		if (objects == null) {
			return "";
		} else if (objects.length == 1) {
			return toJSONString(objects[0]);
		} else {
			List<Object> objs = new LinkedList<Object>();
			for (Object obj : objects) {
				objs.add(obj);
			}

			return toJSONString(objs);
		}
	}
}
